package com.jollychic.aspect;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * Created by jolly on 2019/4/19.
 */
@Aspect
@Component
public class LogAspect {

    private Logger logger = Logger.getLogger(getClass());

    @Pointcut("execution(public * com.jollychic.controller..*.*(..))")
    public void LogAspect() {

    }

    /**
     * 请求之前记录
     * @param joinPoint
     * @throws Throwable
     */
    @Before("LogAspect()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        //接收到请求
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求内容
        logger.info("------------------------request-------------------------");
        logger.info("URL : " + request.getRequestURL().toString());
        logger.info("HTTP_METHOD : " + request.getMethod());
        logger.info("IP : " + request.getRemoteAddr());
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = enu.nextElement();
            logger.info("name:" + name + "value:" + request.getParameter(name));
        }
    }

    /**
     * 请求返回之前记录
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "LogAspect()")
    public void doAfterReturning(Object ret) throws Throwable {
        logger.info("------------------------response------------------------");
        logger.info("RESPONSE : " + ret);
    }
}